package cuit.repositories;

import java.util.List;

import java.sql.*;
import java.util.*;
import cuit.util.Database;
import cuit.domain.Blog;

public class BlogRepository {
	private Connection connection = null;

	public BlogRepository() {
		connection = Database.getConnection();
	}

	/**
	 * 添加blog文章
	 * 
	 * @param blog
	 */
	public void addBlog(Blog blog) {
		try {
			PreparedStatement preparedStatement = connection
					.prepareStatement("insert into t_blog(title,content,publish) values (?, ?, ? )");
			preparedStatement.setString(1, blog.getTitle());
			preparedStatement.setString(2, blog.getContent());
			preparedStatement.setDate(3, new java.sql.Date(blog.getPublish()
					.getTime()));
			preparedStatement.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 删除blog文章
	 * 
	 * @param blogId
	 */
	public void deleteBlog(Long blogId) {
		try {
			PreparedStatement preparedStatement = connection
					.prepareStatement("delete from t_blog where id=?");
			preparedStatement.setLong(1, blogId);
			preparedStatement.executeUpdate();

		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 修改blog文章
	 * 
	 * @param blog
	 */
	public void updateBlog(Blog blog) {
		try {
			PreparedStatement preparedStatement = connection
					.prepareStatement("update t_blog set title=?, content=?, publish=?"
							+ "where id=?");
			preparedStatement.setString(1, blog.getTitle());
			preparedStatement.setString(2, blog.getContent());
			preparedStatement.setDate(3, new java.sql.Date(blog.getPublish()
					.getTime()));
			preparedStatement.setLong(4, blog.getId());
			preparedStatement.executeUpdate();

		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 获取全部blog文章
	 * 
	 * @return
	 */
	public List<Blog> getAllBlogs() {
		List<Blog> blogs = new ArrayList<Blog>();
		try {
			Statement statement = connection.createStatement();
			ResultSet rs = statement.executeQuery("select * from t_blog");
			while (rs.next()) {
				Blog blog = new Blog();
				blog.setId(rs.getLong("id"));
				blog.setTitle(rs.getString("title"));
				blog.setContent(rs.getString("content"));
				blog.setPublish(rs.getDate("publish"));
				blogs.add(blog);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}

		return blogs;
	}

	public Blog getBlogById(String blogId) {
		Blog blog = new Blog();
		try {
			PreparedStatement preparedStatement = connection
					.prepareStatement("select * from t_blog where id=?");
			preparedStatement.setString(1, blogId);
			ResultSet rs = preparedStatement.executeQuery();

			if (rs.next()) {
				blog.setId(rs.getLong("id"));
				blog.setTitle(rs.getString("title"));
				blog.setContent(rs.getString("content"));
				blog.setPublish(rs.getDate("publish"));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}

		return blog;
	}
}
